<?php

/*	Created by Alexander Alexandrov aka SS

			hazg@mail.ru				*/

define('SSLIB_Template', TRUE);
if(!defined("SSLIB_Html")) die(__FILE__." Html class missing");

function subtemplatesReplaceCallback($math)
{
	global $sslib_citeroot;
	$arr = array();
	$vars = explode("||", $math[1]);
	$path = $sslib_citeroot."templates/".str_replace("\t",'',str_replace("\n",'',$vars[0])).".htm";
	$vars[0] = "";
	if(!file_exists($path))
	{
		throw new ErrPage("������ �������� ������� ".$path);
		return "";
	}
	
	foreach($vars as $var)
	{
		if($v = explode("==>",$var))
		{
			if(isset($v[1]))
				$arr[$v[0]] = trim($v[1]);
		}
	}
	return Template::CompileFile($arr, $path);
	

}
function blocksReplaceCallback($match)
{
	global $sslib_citeroot;
	$path = $sslib_citeroot."blocks/".$match[1].".htm";
	
	if(!file_exists($path))
	{
		throw new ErrPage("������ �������� ����� ".$path);
		return "";
	}
	$text = Html::ExecFile($path);

	return $text;
}

/*
 * 
 * TODO: Optimize, check for Err localization
 */
class Template
{
	static function CompileFile($arr, $templ, $insertBR = false)
	{
		global $g_sslib_templates;
		$md5 = $templ;
		if(!array_key_exists($md5, $g_sslib_templates)) 
		{
			if(!is_file($templ)) throw new Err(__T('file not found').": $templ");
			$g_sslib_templates[$md5] = file_get_contents($templ);
			
		}
		$templ = $g_sslib_templates[$md5];
				
		return Template::Compile($arr, $templ, $insertBR);
	}
	static function Compile($arr, $templ, $insertBR = false)
	{		
		//$templ = Template::makeBlocks($templ);
		/*$templ = preg_replace('/{file:([\w\/\.\-\_]+)?}/', '<?include("$1");?>', $templ);*/
		
		foreach($arr as $key => $val)
		{
			$templ = str_replace('{' . $key . '}', $insertBR?nl2br($val):$val, $templ);
		}
		/*$templ = Template::makeSubTemplates($templ);*/
		return Html::Exec($templ, 'template');
	}
	private static function makeSubTemplates($templ)
	{
		return preg_replace_callback('/{template:(.*)?}/is', "subtemplatesReplaceCallback", $templ);
	}
	private static function makeBlocks($page)
	{
		return preg_replace_callback('/{block:([\w\/]+)?}/', "blocksReplaceCallback", $page);
	}

}
?>